<template>
    <div class="wrap">
        <!--文本输入，密码输入，数字输入-->
        <template v-if="field.type === 'text' || field.type === 'password' || field.type === 'number'">
            <div class="field-wrap">
                <input class="field-ipt"
                        v-model="myValue"
                        :disabled="disabled"
                        :type="field.type"
                        :placeholder="disabled ? '' : field.placeholder || '请输入'"
                        :style="{'text-align': align}"
                        @blur="onBlur">
                <div class="icon-wrap"><van-icon class="icon" name="close" v-show="myValue" @click="onClear" v-if="!disabled"></van-icon></div>

            </div>
        </template>
        <!--多行文本-->
        <template v-if="field.type === 'textarea'">
            <div class="field-wrap">
                <textarea class="field-area"
                          v-model="myValue"
                          :disabled="disabled"
                          :type="field.type"
                          :placeholder="disabled ? '' : field.placeholder || '请输入'"
                          @blur="onBlur"
                ></textarea>
                <input>

            </div>
        </template>

        <!--单选框-->
        <template v-if="field.type === 'radio'">
            <div class="field-wrap" :style="{'justify-content': align === 'right' ? 'flex-end' : 'flex-start'}">
                <van-radio-group
                        v-model="myValue"
                        :direction="field.direction || 'horizontal'"
                        :disabled="disabled"
                        @change="onBlur"
                >
                    <van-radio v-for="(item,index) in field.options" :key="index"
                               :name="item.id"
                    >
                        <template #icon="props">
                            <div class="icon-radio" :class="{active: props.checked}"></div>
                        </template>
                        <div class="h1">{{item.name}}</div>
                    </van-radio>
                </van-radio-group>
            </div>
        </template>

        <!--复选框-->
        <template v-if="field.type === 'checkbox'">
            <div class="field-wrap" :style="{'justify-content': align === 'right' ? 'flex-end' : 'flex-start'}">

                <van-checkbox-group v-model="myValue"
                                    :direction="field.direction || 'horizontal'"
                                    :disabled="disabled"
                                    @change="onBlur"
                >
                    <van-checkbox v-for="(item,index) in field.options" :key="index" shape="square" checked-color="#24C373"
                                  :name="item.id">{{item.name}}</van-checkbox>
                </van-checkbox-group>
            </div>
        </template>

        <!--选择列表-->
        <template v-if="field.type === 'picklist'">
            <div class="field-wrap">
                <input class="field-ipt"
                       v-model="myValue"
                       readonly
                       :type="field.type"
                       :placeholder="disabled ? '' : field.placeholder || '请选择'"
                       :style="{'text-align': align}"
                       @click="onShow">
                <div class="icon-wrap">
                    <van-icon class="icon" name="arrow" v-show="!myValue || disabled"></van-icon>
                    <van-icon class="icon" name="close" v-show="myValue" @click="onClear" v-if="!disabled"></van-icon>
                </div>

            </div>
            <m-select v-model="show" :options="field.options" @select="onSelect" :entity-key="field.entityKey"></m-select>
        </template>

        <!--上传图片-->
        <template v-if="field.type === 'picture'">
            <div class="field-wrap" :style="{'justify-content': align === 'right' ? 'flex-end' : 'flex-start'}">
                <van-uploader
                        preview-size="32"
                        :file-list="picList"
                        :before-read="beforeRead"
                        :after-read="afterRead"
                        :show-upload="!disabled"
                        :deletable="!disabled"
                        :disabled="disabled"
                        :max-count="field.maxCount"
                        :preview-options="previewOptions"
                        @delete="deleteFile"
                ></van-uploader></div>

        </template>

        <!--日历选择--开发中-->
        <template v-if="field.type === 'date'">
            <div class="field-wrap">
                <input class="field-ipt"
                       v-model="myValue"
                       readonly
                       :placeholder="disabled ? '' : field.placeholder || '请选择'"
                       :style="{'text-align': align}"
                       @click="onShowCalendar"
                >
                <div class="icon-wrap">
                    <van-icon class="icon" name="arrow" v-show="!myValue || disabled"></van-icon>
                    <van-icon class="icon" name="close" v-show="myValue" @click="onClear" v-if="!disabled"></van-icon>
                </div>

            </div>
            <van-calendar v-model="showCalendar" @confirm="onConfirmCalendar" color="#24C373" />
        </template>
    </div>
</template>

<script>
  import select from '@/components/select/select'
  import {Uploader, RadioGroup, Radio, Calendar,Checkbox, CheckboxGroup} from 'vant'
  import {uploadFile} from "../../request/api";
  import {imgCompress, crtTimeFtt} from "../../utils/utils";

  /**
   * @description
   * props-
   * field:
   * field_id {String}: 字段id
   * type{String}：字段类型（text、password、number、radio、picklist、picture、date、checkbox
   * label{String}：字段名称
   * message{String}： 字段名称下的提示信息
   * placeholder{String}：输入框占位符
   * rule {Array}验证规则
   * picLimit {Number} 图片显示数量
   * options {Array}：picklist类型选项
   * entityKey{String}：选项中对象显示的字段id
   */

  // const http = process.env.VUE_APP_PATH;
  const http = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PATH : window.webConfig.webApiBasePath;
  export default {
    name: "m-field",
    components: {
      "m-select": select,
      [Uploader.name]: Uploader,
      [RadioGroup.name]: RadioGroup,
      [Radio.name]: Radio,
      [Calendar.name]:Calendar,
      [Checkbox.name]: Checkbox,
      [CheckboxGroup.name]: CheckboxGroup
    },
    props: {
      field: {},
      value: {},
      disabled: {},
      align: {
        default: 'right'
      }
    },
    watch: {
      value:{
        handler(val){
          if (this.field.type === 'picture'){
            let arr = val && val.split(',') || [],
              pics = [];
            arr.forEach(item => {
              pics.push({url: http + item,id: item})
            });
            this.picList = pics;
          }
          this.myValue = val;

        },
        immediate: true
      },
      field: {
        handler(val){
          if (val.defaultValue && !this.value){
            this.myValue = val.defaultValue;
            this.handleTrigger(this.myValue)
          }
        },
        immediate: true
      },
    },
    data(){
      return {
        myValue: '',
        show: false,

        picList: [],

        radio: '1',

        previewOptions:{
          overlayStyle: {
            "background": "rgba(0,0,0,0.5)"
          }
        },

          showCalendar: false
      }
    },
    methods: {
      //清空
      onClear(){
        this.myValue = '';
        this.handleTrigger('');
      },
      onBlur(){
        this.handleTrigger(this.myValue)
      },
      //弹出层显示（选择）
      onShow(){
        if (this.disabled)return;
        this.show = true;
      },
      //选择框选中
      onSelect(data){
        this.handleTrigger(data);

        let {entityKey} = this.field,
          val = typeof data === 'string' ? data : data[entityKey || 'name'];
        this.myValue = val;
      },
      //  选择文件前
      beforeRead(file){
        console.log('读取文件前',file);
        if (this.field.beforeRead){
          return this.field.beforeRead(file);
        }
        return new Promise(resolve => {
          //文件超出500k压缩
          // if (file.size < 512000) resolve(file)
          if (file.size < 204800) resolve(file) //超出200k
          else imgCompress(file).then(f => resolve(f))
        })
      },
      //选择图片后操作
      afterRead(e){
        console.log('选择文件后：',e);
        const formData = new FormData();
        formData.append('file',e.file)
        uploadFile(formData).then(res => {
          if (res.errcode !== 0)return;
          let data = res.row[0];
          if (this.field.picLimit === 1){
            this.picList = [{name: data.shortName,url: http + data.url,id: data.url}]
          }
          else this.picList = [...this.picList,{name: data.shortName,url: http + data.url,id: data.url}];
          this.picChange();

        });
      },
      //删除图片
      deleteFile(e){
        let index = this.picList.findIndex(item => item.url === e.url);
        this.picList.splice(index,1);
        this.picChange();
      },
      //  图片变化
      picChange(){
        let files = [];
        this.picList.forEach(item => {
          files.push(item.id);
        });
        this.handleTrigger(files.join(','));
      },
      //  弹出日历
      onShowCalendar(){
        if (this.disabled)return;
        this.showCalendar = true;
      },
      //选择日历
      onConfirmCalendar(date){
        let val = crtTimeFtt(date,'YYYY-MM-DD')
        this.handleTrigger(val)
        this.myValue = val;
        this.showCalendar = false;
      },

      handleTrigger(val){
        let obj = {
          field: this.field,
          val
        }
        this.$emit('change',obj)
      }
    }
  }
</script>


<style scoped lang="less">
.wrap{
    height: 100%;
    width: 100%;
}
.field-wrap{
    font-size: 15px;
    width: 100%;
    display: flex;
    height: 100%;
    align-items: center;
    flex-wrap: wrap;
    .field-ipt,.field-area{
        flex: 1;
        width: 0;
        height: 100%;
        color: #333;
        font-size: 15px;
        &::placeholder{
            color: #b3b3b3;
            font-size: 13px;
        }
        &:disabled,
        &[disabled] {
            -webkit-text-fill-color: #333;
            opacity: 1;
        }
    }
    .field-area{
        height: 90px;
        flex: unset;
        width: 100%;
        border: none;
    }
    .icon-wrap{
        height: 100%;
    }
    .icon{
        height: 100%;
        display: flex;
        align-items: center;
        padding: 0 4px;
    }
    input{
        background: none;
    }

    ::v-deep{
        .van-uploader__wrapper--disabled{
            opacity: 1;
        }
    }
}
</style>
